<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    canvas {
      display: block;
      background-color: #000;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  <script>
    const canvas = document.querySelector('#canvas')
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight

    const ctx = canvas.getContext('2d')

    class Ball {
      constructor() {
        this.x = 525
        this.y = 140
        this.vx = 3
        this.vy = 4
        this.r = 50
        this.color = 'orange'
      }

      drawBall() {
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2)
        ctx.fillStyle = this.color
        ctx.fill()


        ctx.beginPath()
        ctx.fillStyle = 'white'
        ctx.font = 'bold 30px Arial'
        ctx.textAlign = 'left'
        ctx.fillText('对象', this.x - this.r / 2, this.y)

      }

      move() {
        // 清除之前绘制的图片
        ctx.clearRect(0, 0, canvas.width, canvas.height)

        ctx.beginPath()
        ctx.lineWidth = 15
        ctx.strokeStyle = 'purple'
        ctx.strokeRect(460, 76, 1000, 800)

        this.drawBall()

        if (this.x < 525 || this.x > 1400) this.vx *= -1 // 反复横跳
        if (this.y < 140 || this.y > 810) this.vy *= -1 // 反复横跳

        // 数据更新模块
        this.x += this.vx
        this.y += this.vy

      }
    }

    const ball = new Ball()
    // ball.move()

    setInterval(() => {
      ball.move()
    }, 1000 / 60)
  </script>
</body>

</html>